package model

import (
	Mysql "gin/database"
)

type Auth struct {
	Id        int64  `json:"id" gorm:"column:id"`
	AccessKey string `json:"access_key" gorm:"column:access_key"`
	SecretKey string `json:"secret_key" gorm:"column:secret_key"`
}

// 设置表名
func (Auth) TableName() string {
	return "auth"
}

func (this *Auth) Generate() (accessKey string, secretKey string, err error) {

	query := new(Auth)
	Mysql.DB.First(&query)

	if query.Id > 0 {
		// 存在token 配置，更新操作
		this.Id = query.Id
		resultUpdate := Mysql.DB.Save(&this)
		if resultUpdate.Error != nil {
			err = resultUpdate.Error
			return
		}
	} else {
		// 不存在插入操作
		resultCreate := Mysql.DB.Create(&this)
		if resultCreate.Error != nil {
			err = resultCreate.Error
			return
		}
	}

	accessKey = this.AccessKey
	secretKey = this.SecretKey
	return
}

func (this *Auth) GetToken() (accessKey string, secretKey string, err error) {
	result := Mysql.DB.First(&this)
	if this.Id == 0 {
		err = result.Error
		return
	} else {
		accessKey = this.AccessKey
		secretKey = this.SecretKey
	}
	return
}
